package com.igame.config;

import com.igame.Service.UserService;
import com.igame.common.Result;
import com.igame.dto.UserDto;
import com.igame.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;

public class CustomAuthenticationProvider implements AuthenticationProvider {

    @Autowired
    private UserService userService;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        String username = authentication.getName();
        String password = authentication.getCredentials().toString();

        // 调用 UserService 进行用户认证
        UserDto userDto = new UserDto();
        userDto.setUsername(username);
        userDto.setPassword(password);

        Result<User> result = userService.login(userDto);

        if (result.getState()) {
            // 认证成功，返回一个认证对象
            return new UsernamePasswordAuthenticationToken(username, password, null);
        } else {
            // 认证失败，抛出异常
            throw new BadCredentialsException("用户名或密码错误");
        }
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return false;
    }
}
